<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="分类名称" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['fieldType:add']">新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['fieldType:edit']">修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['fieldType:remove']">删除</el-button>-->
<!--      </el-col>-->
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['fieldType:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="FieldTypeList" @selection-change="handleSelectionChange" row-key="id" lazy :load="loadChildren" :tree-props="{children: 'childrenList', hasChildren: 'exitSon'}">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="父类名称" align="center" prop="typeName" />
<!--      <el-table-column label="父类名称" align="center" prop="parentName" >-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.parentName">{{scope.row.parentName}}</span>-->
<!--          <span v-else>—</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="目录类型" align="center" prop="systemCatalogName" ></el-table-column>-->
<!--      <el-table-column label="对应关键词" align="center" prop="keyWords" />-->
      <el-table-column label="分类排序" align="center" prop="sort"/>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['fieldType:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['fieldType:remove']">删除</el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-setting" @click="handleSetting(scope.row)" v-hasPermi="['fieldType:remove']">设置</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改引擎信息信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="typeForm" :model="typeForm" :rules="rules" label-width="100px">

        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="typeForm.typeName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="typeForm.sort" placeholder="请输入分类名称排列顺序" />
        </el-form-item>
        <el-form-item label="父类名称" prop="parentId">
          <el-cascader :options="options" :props="{ checkStrictly: true }" clearable v-model.number="typeForm.parentId"  @change="handleChange">
          </el-cascader>
<!--        <el-cascader :options="options" v-model.number="typeForm.parentId"  @change="handleChange">-->
<!--            <template slot-scope="{ node, data }">-->
<!--              <span>{{ data.typeName }}</span>-->
<!--              <span v-if="!data.childrenList"> ({{ data.childrenList.length }}) </span>-->
<!--            </template>-->
<!--          </el-cascader>-->
        </el-form-item>
<!--        <el-form-item label="对应关键词" prop="keyWords">-->
<!--          <el-input v-model="form.keyWords" placeholder="请输入对应关键词" />-->
<!--        </el-form-item>-->
        <!-- <el-form-item label="关键词" prop="keyWords">
          <el-tag v-for="(tag,index) in keywords" :key="index" closable :disable-transitions="false" @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Keyword</el-button>
        </el-form-item>
        -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="typeForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFieldType,
  getFieldType,
  delFieldType,
  addFieldType,
  updateFieldType,
  listAllFieldType,
} from "@/api/qysj/app/FieldType.js";
import { addCategory, delCategory, editCategory, getCategory, getCategoryAll } from '@/api/qysj/app/rawData/field'

export default {
  name: "FieldType",
  data() {
    return {
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      typeNames:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 引擎信息信息表格数据
      FieldTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      settingOpen:false,
      //对话框宽度
      formLabelWidth:'80px',
      // 对话框表单设置
      settingForm:{
        userLevel:[],
        userType:[],
        specificUser:[]
      },
      // 模拟用户类型，用户级别，指定用户数据
      userLevels: [
        { label: '初级', value: 'primary' },
        { label: '中级', value: 'middle' },
        { label: '高级', value: 'senior' },
        // Add more options as needed
      ],
      userTypes: [
        { label: '个人', value: 'type1' },
        { label: '企业', value: 'type2' },
        { label: '政府人员', value: 'type3' },
        // Add more options as needed
      ],
      specifiedUsers: [
        { label: '张三', value: 'user1' },
        { label: '李四', value: 'user2' },
        { label: '王麻子', value: 'user3' },
        { label: 'zcl', value: 'user4' },
        { label: '张欣悦', value: 'user5' },
        // Add more options as needed
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        catalogTypes:'0,1,2'
      },
      // 表单参数
      typeForm: {},
      keywords:[],
      inputVisible: false,
      inputValue: '',
      // 表单校验
      rules: {
        auditId: [
          { required: true, message: "审核Id不能为空", trigger: "blur" },
        ],
        createUserId: [
          { required: true, message: "创建用户ID不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    /** 查询信息信息列表 */
    getList() {
      this.loading = true;
      getCategory(this.queryParams).then((response) => {
        if (response.code===200){
          this.FieldTypeList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      });
    },
    loadChildren(tree, treeNode, resolve){
      let Params = {
        pageNum: 1,
        pageSize: 30,
        parentId:tree.id
      }
      listFieldType(Params).then((response) => {
        resolve(response.rows);
      });

    },
    getOptions() {
      getCategoryAll().then(res=>{
        if (res.code===200){
          const propertyMap={
            'childrenList':'children',
            'id':'value',
            'typeName':"label"
          }
          this.options=res.data;
          this.options.forEach((item,index)=>this.renameProperties(item,propertyMap))
          console.log('this.options', this.options)
        }
      })
    },
    // 级联选择器更改属性名
    renameProperties(obj, propertyMap) {
      for (let key in obj) {
        if (obj[key] && typeof obj[key] === 'object') {
          this.renameProperties(obj[key], propertyMap);
        }
        if (propertyMap[key]) {
          obj[propertyMap[key]] = obj[key];
          delete obj[key];
        }
      }
},
    handleChange(val){
      console.log('val', val)
      this.typeForm.parentId=val[val.length-1]
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.typeForm = {
        id: null,
        parentId: '0',
        remark: "",
        sort: 0,
        typeName: ""
      };
      this.resetForm("typeForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.typeNames = selection.map((item) => item.typeName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分类信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.typeForm=row
      this.title = "修改分类信息";
      this.open = true;
    },
    //新增或修改分类提交按钮 */
    submitForm() {
      this.$refs["typeForm"].validate((valid) => {
        if (valid) {
          console.log('this.typeForm', this.typeForm.id);
          if (!this.typeForm.id){
            addCategory(JSON.stringify(this.typeForm)).then(res=>{
              if (res.code===200){
                this.$modal.msgSuccess("新增成功");
                this.open=false;
                this.getList()
              }else {
                this.$modal.msgError("新增失败");
              }
            })
          }else {
            editCategory(JSON.stringify(this.typeForm)).then(res=>{
              if (res.code===200){
                this.$modal.msgSuccess("修改成功");
                this.open=false;
                this.getList()
              }else {
                this.$modal.msgError("修改失败");
              }
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const typeName=row.typeName || this.typeName
      console.log(ids);
      this.$modal
        .confirm('是否确认删除分类名称为"' + row.typeName + '"的数据项？')
        .then(function () {
          return delCategory(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   this.download(
    //     "fieldType/export",
    //     {
    //       ...this.queryParams,
    //     },
    //     `FieldType_${new Date().getTime()}.xlsx`
    //   );
    // },
  },
};
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
